package com.leyou.auth.config;

import com.leyou.auth.task.PrivilegeTokenHolder;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: wangzibeng
 * Date: 2019/5/16 0016
 * Time: 16:18
 */

@Configuration
public class PrivilegeConfig {
    @Bean
    public RequestInterceptor requestInterceptor(JwtProperties prop, PrivilegeTokenHolder privilegeTokenHolder) {
        return new PrivilegeFeignInterceptor(prop, privilegeTokenHolder);
    }

    /**
     * 自定义Feign的请求拦截器,在请求头中添加认证token
     */
    @Slf4j
    static class PrivilegeFeignInterceptor implements RequestInterceptor {
        private JwtProperties jwtProperties;
        private PrivilegeTokenHolder privilegeTokenHolder;

        PrivilegeFeignInterceptor(JwtProperties prop, PrivilegeTokenHolder privilegeTokenHolder) {
            this.jwtProperties = prop;
            this.privilegeTokenHolder = privilegeTokenHolder;
        }

        @Override
        public void apply(RequestTemplate requestTemplate) {
            log.info("添加请求验证token!");
            JwtProperties.PrivilegeTokenProperties prop = jwtProperties.getPrivilege();
            requestTemplate.header(prop.getHeaderName(), privilegeTokenHolder.getToken());
        }
    }
}
